package com.itheima.stargraph.service;

import com.itheima.stargraph.pojo.ComfyuiModel;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;


/**
 * Freemarker组件类
 *
 * @Author mr.Du
 * @Date 2025/6/11 2025/6/11
 */
@Component
public class FreemarkerService {

    @Autowired
    private Configuration configuration;

    /**
     * 基于模型数据使用Freemarker渲染出工作流JSON字符串
     *
     * @param comfyuiModel
     * @return
     */
    public String render(ComfyuiModel comfyuiModel) {

        try {
            //1.获取模版对象
            Template template = configuration.getTemplate("workflow.ftl");

            //2.准备模型数据
            HashMap<String, ComfyuiModel> modelMap = new HashMap<>();
            modelMap.put("config", comfyuiModel);

            //3.准备输出流
            StringWriter out = new StringWriter();

            //4. 执行渲染
            template.process(modelMap, out);

            //5. 获取渲染结果
            String workflowJSON = new String(out.toString().getBytes(StandardCharsets.UTF_8));

            return workflowJSON;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return null;
    }

}